package com.atldy.commerce.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheKey;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @version 1.0
 * @Author: li-dong-yang
 * @CreateTime: 2021-09-12 21:22
 * @Description： 注解方式Hystrix实现请求缓存
 */
@Service
@Slf4j
public class CacheHystrixAnnotationsCommond {

    @Autowired
    private NacosClientService nacosClientService;


    // 第一种 Hystrix Cache 注解的使用方法

    @CacheResult(cacheKeyMethod = "getcacheKey")
    @HystrixCommand(commandKey = "CacheHystrixAnnotationsCommond")
    public List<ServiceInstance> cacheServiceInstances01(String serviceId) {
        log.info("get ServiceInstance cacheServiceInstances01 serviceId [{}]", serviceId);
        return nacosClientService.getServiceInstance(serviceId);
    }

    public String getcacheKey(String cacheId) {
        return cacheId;
    }


    @CacheRemove(commandKey = "CacheHystrixAnnotationsCommond", cacheKeyMethod = "getcacheKey")
    @HystrixCommand
    public void clearRequestCach01(String cacheId) {
        log.info("clear hystrix clearRequestCach01 key: [{}]", cacheId);
    }

    // 第二种注解方式
    @CacheResult
    @HystrixCommand(commandKey = "CacheHystrixAnnotationsCommond")
    public List<ServiceInstance> cacheServiceInstances02(@CacheKey String serviceId) {
        log.info("get ServiceInstance cacheServiceInstances02 serviceId [{}]", serviceId);
        return nacosClientService.getServiceInstance(serviceId);
    }


    @CacheRemove(commandKey = "CacheHystrixAnnotationsCommond")
    @HystrixCommand
    public void clearRequestCach02(@CacheKey String cacheId) {
        log.info("clear hystrix clearRequestCach02 key: [{}]", cacheId);
    }

    //第三种注解实现方式
    @CacheResult
    @HystrixCommand(commandKey = "CacheHystrixAnnotationsCommond")
    public List<ServiceInstance> cacheServiceInstances03(String serviceId) {
        log.info("get ServiceInstance cacheServiceInstances03 serviceId [{}]", serviceId);
        return nacosClientService.getServiceInstance(serviceId);
    }


    @CacheRemove(commandKey = "CacheHystrixAnnotationsCommond")
    @HystrixCommand
    public void clearRequestCach03(String cacheId) {
        log.info("clear hystrix clearRequestCach03 key: [{}]", cacheId);
    }


}